<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>打印文件上传</span>
      </div>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card class="upload-card">
            <div slot="header">
              <span>单文件上传</span>
            </div>
            <el-upload
              class="upload-demo"
              drag
              :action="uploadUrl"
              :headers="headers"
              :before-upload="beforeUpload"
              :on-success="handleSuccess"
              :on-error="handleError"
              :show-file-list="false"
              accept=".pdf,.doc,.docx,.txt,.jpg,.jpeg,.png,.bmp,.tiff"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip" slot="tip">
                支持的文件类型：PDF、DOC、DOCX、TXT、JPG、PNG、BMP、TIFF<br>
                文件大小不超过 50MB
              </div>
            </el-upload>
          </el-card>
        </el-col>
        
        <el-col :span="12">
          <el-card class="upload-card">
            <div slot="header">
              <span>批量文件上传</span>
            </div>
            <el-upload
              class="upload-demo"
              drag
              multiple
              name="files"
              :action="batchUploadUrl"
              :headers="headers"
              :before-upload="beforeBatchUpload"
              :on-success="handleBatchSuccess"
              :on-error="handleError"
              :limit="10"
              :on-exceed="handleExceed"
              accept=".pdf,.doc,.docx,.txt,.jpg,.jpeg,.png,.bmp,.tiff"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip" slot="tip">
                支持的文件类型：PDF、DOC、DOCX、TXT、JPG、PNG、BMP、TIFF<br>
                文件大小不超过 50MB，一次最多上传10个文件
              </div>
            </el-upload>
          </el-card>
        </el-col>
      </el-row>

      <!-- 上传结果展示 -->
      <el-card class="result-card" v-if="uploadResults.length > 0">
        <div slot="header">
          <span>上传结果</span>
          <el-button style="float: right; padding: 3px 0" type="text" @click="clearResults">清空</el-button>
        </div>
        <el-table :data="uploadResults" style="width: 100%">
          <el-table-column prop="originalName" label="文件名" width="200" />
          <el-table-column prop="fileSize" label="文件大小" width="120">
            <template slot-scope="scope">
              {{ formatFileSize(scope.row.fileSize) }}
            </template>
          </el-table-column>
          <el-table-column prop="fileType" label="文件类型" width="100" />
          <el-table-column prop="status" label="状态" width="100">
            <template slot-scope="scope">
              <el-tag :type="scope.row.status === 'success' ? 'success' : 'danger'">
                {{ scope.row.status === 'success' ? '成功' : '失败' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="message" label="消息" />
          <el-table-column label="操作" width="150">
            <template slot-scope="scope">
              <el-button
                v-if="scope.row.status === 'success'"
                size="mini"
                type="primary"
                @click="viewFile(scope.row)"
              >查看</el-button>
              <el-button
                v-if="scope.row.status === 'success'"
                size="mini"
                type="danger"
                @click="deleteFile(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 文件统计 -->
      <el-card class="stats-card">
        <div slot="header">
          <span>文件统计</span>
        </div>
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-number">{{ stats.total }}</div>
              <div class="stat-label">总文件数</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-number">{{ stats.document }}</div>
              <div class="stat-label">文档文件</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-number">{{ stats.image }}</div>
              <div class="stat-label">图片文件</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-number">{{ formatFileSize(stats.totalSize) }}</div>
              <div class="stat-label">总大小</div>
            </div>
          </el-col>
        </el-row>
      </el-card>
    </el-card>
  </div>
</template>

<script>
import { uploadPrintFile, batchUploadPrintFiles, getSupportedTypes, deleteOssFile } from "@/api/print/file";
import { getToken } from "@/utils/auth";

export default {
  name: "PrintFileUploadPage",
  data() {
    return {
      uploadUrl: process.env.VUE_APP_BASE_API + '/print/file/upload',
      batchUploadUrl: process.env.VUE_APP_BASE_API + '/print/file/batch-upload',
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      uploadResults: [],
      stats: {
        total: 0,
        document: 0,
        image: 0,
        totalSize: 0
      },
      supportedTypes: {
        document: [],
        image: [],
        maxSize: '50MB'
      }
    };
  },
  created() {
    this.getSupportedTypes();
  },
  methods: {
    // 获取支持的文件类型
    getSupportedTypes() {
      getSupportedTypes().then(response => {
        this.supportedTypes = response.data;
      });
    },
    
    // 单文件上传前验证
    beforeUpload(file) {
      const isValidType = this.checkFileType(file);
      const isValidSize = this.checkFileSize(file);
      
      if (!isValidType) {
        this.$message.error('不支持的文件类型！');
        return false;
      }
      
      if (!isValidSize) {
        this.$message.error('文件大小不能超过50MB！');
        return false;
      }
      
      this.$message.info('开始上传文件...');
      return true;
    },
    
    // 批量上传前验证
    beforeBatchUpload(file) {
      const isValidType = this.checkFileType(file);
      const isValidSize = this.checkFileSize(file);
      
      if (!isValidType) {
        this.$message.error(`文件 ${file.name} 类型不支持！`);
        return false;
      }
      
      if (!isValidSize) {
        this.$message.error(`文件 ${file.name} 大小超过限制！`);
        return false;
      }
      
      return true;
    },
    
    // 检查文件类型
    checkFileType(file) {
      const allowedTypes = [
        ...this.supportedTypes.document,
        ...this.supportedTypes.image
      ];
      const extension = file.name.split('.').pop().toLowerCase();
      return allowedTypes.includes(extension);
    },
    
    // 检查文件大小
    checkFileSize(file) {
      const maxSize = 50 * 1024 * 1024; // 50MB
      return file.size <= maxSize;
    },
    
    // 单文件上传成功
    handleSuccess(response, file) {
      if (response.code === 200) {
        this.$message.success('文件上传成功！');
        this.uploadResults.unshift({
          originalName: file.name,
          fileSize: file.size,
          fileType: response.data.fileType,
          status: 'success',
          message: '上传成功',
          fileUrl: response.data.fileUrl,
          id: response.data.id
        });
        this.updateStats();
      } else {
        this.$message.error(response.msg || '上传失败！');
        this.uploadResults.unshift({
          originalName: file.name,
          fileSize: file.size,
          fileType: 'unknown',
          status: 'error',
          message: response.msg || '上传失败'
        });
      }
    },
    
    // 批量上传成功
    handleBatchSuccess(response, file, fileList) {
      if (response.code === 200) {
        this.$message.success('批量上传完成！');
        const results = response.data.results;
        results.forEach(result => {
          this.uploadResults.unshift({
            originalName: result.originalName,
            fileSize: result.fileSize || 0,
            fileType: result.fileType,
            status: result.id ? 'success' : 'error',
            message: result.remark || (result.id ? '上传成功' : '上传失败'),
            fileUrl: result.fileUrl,
            id: result.id
          });
        });
        this.updateStats();
      } else {
        this.$message.error(response.msg || '批量上传失败！');
        // 处理失败的文件
        if (fileList && fileList.length > 0) {
          fileList.forEach(file => {
            this.uploadResults.unshift({
              originalName: file.name,
              fileSize: file.size,
              fileType: 'unknown',
              status: 'error',
              message: response.msg || '上传失败',
              fileUrl: null,
              id: null
            });
          });
        }
      }
    },
    
    // 上传失败
    handleError(err, file, fileList) {
      this.$message.error('文件上传失败！');
      
      // 处理单个文件失败
      if (file) {
        this.uploadResults.unshift({
          originalName: file.name,
          fileSize: file.size,
          fileType: 'unknown',
          status: 'error',
          message: '上传失败'
        });
      }
      
      // 处理批量上传失败
      if (fileList && fileList.length > 0) {
        fileList.forEach(fileItem => {
          this.uploadResults.unshift({
            originalName: fileItem.name,
            fileSize: fileItem.size,
            fileType: 'unknown',
            status: 'error',
            message: '上传失败'
          });
        });
      }
    },
    
    // 文件数量超出限制
    handleExceed() {
      this.$message.warning('一次最多只能上传10个文件！');
    },
    
    // 查看文件
    viewFile(file) {
      if (file.fileUrl) {
        window.open(file.fileUrl, '_blank');
      }
    },
    
    // 删除文件
    deleteFile(file) {
      this.$confirm('确认删除该文件吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (file.fileUrl) {
          deleteOssFile(file.fileUrl).then(response => {
            this.$message.success('删除成功！');
            const index = this.uploadResults.findIndex(item => item.id === file.id);
            if (index > -1) {
              this.uploadResults.splice(index, 1);
              this.updateStats();
            }
          }).catch(() => {
            this.$message.error('删除失败！');
          });
        }
      });
    },
    
    // 清空结果
    clearResults() {
      this.uploadResults = [];
      this.updateStats();
    },
    
    // 更新统计信息
    updateStats() {
      this.stats.total = this.uploadResults.filter(item => item.status === 'success').length;
      this.stats.document = this.uploadResults.filter(item => 
        item.status === 'success' && item.fileType === 'document'
      ).length;
      this.stats.image = this.uploadResults.filter(item => 
        item.status === 'success' && item.fileType === 'image'
      ).length;
      this.stats.totalSize = this.uploadResults
        .filter(item => item.status === 'success')
        .reduce((sum, item) => sum + (item.fileSize || 0), 0);
    },
    
    // 格式化文件大小
    formatFileSize(bytes) {
      if (bytes === 0) return '0 Bytes';
      const k = 1024;
      const sizes = ['Bytes', 'KB', 'MB', 'GB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }
  }
};
</script>

<style scoped>
.upload-card {
  margin-bottom: 20px;
}

.result-card {
  margin-top: 20px;
}

.stats-card {
  margin-top: 20px;
}

.stat-item {
  text-align: center;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 4px;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.upload-demo {
  text-align: center;
}

.el-upload__tip {
  line-height: 1.5;
  margin-top: 10px;
}
</style> 